package com.aiwhose.aiwhosewechatplublicaiwhose.utils;/**
 * @project aiwhose_service
 * @description 非对称加密工具
 * @author Administrator
 * @date 2023/11/21 11:25:18
 * @version 1.0
 */

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.SignUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.crypto.asymmetric.Sign;
import cn.hutool.crypto.asymmetric.SignAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: aiwhose_service
 * @description: 非对称加密工具
 * @author: 田国刚
 * @create: 2023-11-21 11:25
 **/
@Component
public class RSAUtil {
    @Value("${rsa.private-key}")
    private String PRIVATE_KEY;

    @Value("${rsa.public-key}")
    private String PUBLIC_KEY;

    //获取秘钥
    public Map<String, String> generateKeyPair() {
        KeyPair keyPair = SecureUtil.generateKeyPair("RSA");

// 获取生成的公钥和私钥
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();

// 将公钥和私钥转换为 byte[] 形式
        byte[] publicKeyBytes = publicKey.getEncoded();
        byte[] privateKeyBytes = privateKey.getEncoded();

// 使用 Base64 编码转换为字符串形式
        String publicKeyBase64 = Base64.encode(publicKeyBytes);
        String privateKeyBase64 = Base64.encode(privateKeyBytes);
        Map<String, String> map = new HashMap<>();
        map.put("publicKey", publicKeyBase64);
        map.put("privateKey", privateKeyBase64);
        return map;
    }

    // 加密
    public String encrypt(byte[] data) {
        RSA rsa = new RSA(PRIVATE_KEY, PUBLIC_KEY);
        byte[] encrypt = rsa.encrypt(data, KeyType.PublicKey);
        return HexUtil.encodeHexStr(encrypt);
    }

    // 解密
    public byte[] decrypt(String encryptedData) {
        RSA rsa = new RSA(PRIVATE_KEY, PUBLIC_KEY);
        byte[] decrypted = rsa.decrypt(HexUtil.decodeHex(encryptedData), KeyType.PrivateKey);
        return decrypted;
    }

    /**
     * 使用私钥对数据进行签名
     *
     * @param data       要签名的数据
     * @return 签名结果的字节数组
     */
    public byte[] sign(  byte[] data ) {
        Sign sign = SignUtil.sign(SignAlgorithm.SHA256withRSA,PRIVATE_KEY , null);
        return sign.sign(data);
    }

    /**
     * 使用公钥验证签名
     *
     * @param data       原始数据
     * @param signedData 签名后的数据
     * @return 验证签名是否通过
     */
    public boolean verify(  byte[] data, byte[] signedData ) {
        Sign sign = SignUtil.sign(SignAlgorithm.SHA256withRSA, null, PUBLIC_KEY);
        return sign.verify(data, signedData);
    }

}



